<template>
  <el-form :model="form" ref="form" :rules="rules" :label-position="labelPosition" :hide-required-asterisk="true" :size="'mini'" style="margin:0 20px;">
    <el-row>
      <el-col :span="12" style="padding-right: 1%">
        <div class="grid-content bg-purple">
          <el-form-item :label="$t('接口名')" :label-width="formLabelWidthHalf" prop="strPhysicsName" @input="updateView($event)">
            <span>{{ form.strPhysicsName ? form.strPhysicsName : form.strBridgeName }}</span>
          </el-form-item>
          <el-form-item :label="$t('别名')" :label-width="formLabelWidthHalf" @input="updateView($event)" prop="cDevOtherName">
            <el-input v-emoji v-model="form.cDevOtherName" autocomplete="off" ref="name" style="width:275px;"></el-input>
          </el-form-item>
          <el-form-item label="MTU" prop="iMtu" :label-width="formLabelWidthHalf" @input="updateView($event)" v-if="[0, 1, 2].includes(form.enPortMode)">
            <el-input v-emoji v-model="form.iMtu" :disabled='form.enPortMode === 2' ref="mtu" style="width:275px;">
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('自协商开关')" :label-width="formLabelWidthHalf" v-if="[0, 1, 2].includes(form.enPortMode)">
            <el-radio v-model="form.bNegotiateFlag" label="on" :disabled='form.force_autoneg' class="on">{{$t('开启')}}</el-radio>
            <el-radio v-model="form.bNegotiateFlag" label="off" :disabled='form.force_autoneg' class="off">{{$t('关闭')}}</el-radio>
          </el-form-item>
          <el-form-item :label="$t('速率')" prop="bandwidth" :label-width="formLabelWidthHalf" @input="updateView($event)" v-if="[0, 1, 2].includes(form.enPortMode)">
            <el-select v-model="form.bandwidth" ref="bandwidth" :disabled="form.bNegotiateFlag === 'on' || form.force_autoneg" :placeholder="$t('请选择')" style="width: 50%;height: 28px">
              <el-option :label="item + 'M'" :value="item" v-for="item in form.speed_list" :key="item"></el-option>
            </el-select>
            <span class="warning_span">{{ $t(form.bandwidthState) }}</span>
          </el-form-item>
          <el-form-item :label="$t('双工模式')" prop="bDuplexFlag" :label-width="formLabelWidthHalf" @input="updateView($event)" v-if="[0, 1, 2].includes(form.enPortMode)">
            <el-select v-model="form.bDuplexFlag" ref="bDuplexFlag" :disabled="form.bNegotiateFlag === 'on' || form.force_autoneg" :placeholder="$t('请选择')" style="width: 50%;height: 28px">
              <el-option :label="$t('全双工')" :value="'full'"></el-option>
              <el-option :label="$t('半双工')" :value="'half'"></el-option>
            </el-select>
            <span class="warning_span">{{ $t(form.bDuplexFlagState) }}</span>
          </el-form-item>
        </div>
        <div v-if="form.enPortMode === 3">
          <el-form-item :label="$t('对端接口')" :label-width="formLabelWidthHalf" prop="iTransSelectedPort">
            <el-select v-model="form.iTransSelectedPort" ref="port" :placeholder="$t('请选择')">
              <el-option v-for="item in physicsList" :key="item.strPhysicsName" :label="item.strPhysicsName" :value="item.strPhysicsName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('数据允许方向')" :label-width="formLabelWidthHalf">
            <el-radio v-model="form.iTransType" :label="1" class="twoWay">{{$t('双向传输')}}</el-radio>
            <el-radio v-model="form.iTransType" :label="2" class="oneWay">{{$t('单向传输')}}</el-radio>
            <el-select v-model="form.iTransDirecType" ref="direcType" :placeholder="$t('请选择')" v-if="form.iTransType === 2" :style="lang==='zh'?'width:150px;':'width:300px;'">
              <el-option :label="$t('本接口作为入接口')" :value="1"></el-option>
              <el-option :label="$t('本接口作为出接口')" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-col>
      <el-col :span="12" style="padding-left: 1%">
        <el-form-item :label="$t('模式')" :label-width="formLabelWidth">
          <el-radio-group v-model="form.enPortMode" style="line-height:25px;    display: flex;flex-flow: row wrap;" @change="enPortModeChange">
            <el-radio style="width:50%;margin-right:0;margin-bottom:10px" :label="0" class="routerMode">{{$t('路由模式')}}</el-radio>
            <el-radio style="width:50%;margin-right:0;margin-bottom:10px" :label="1" class="transparent">{{$t('透明模式')}}</el-radio>
            <el-radio style="width:50%;margin-right:0;margin-bottom:10px" :label="3" class="fictitious">{{$t('虚拟线模式')}}</el-radio>
            <el-radio style="width:50%;margin-right:0;margin-bottom:10px" :label="2" class="polymerization">{{$t('聚合模式')}}</el-radio>
          </el-radio-group>
          <span style="font-size:12px;color:red;" v-if="form.enPortMode === 3">{{ $t('被设置为虚拟线模式的网口，将失去管理设备能力，请谨慎操作。') }}</span>
        </el-form-item>
        <div class="grid-content bg-purple-light">
          <el-form-item :label="$t('状态')" :label-width="formLabelWidth" v-if="[0, 1, 2].includes(form.enPortMode)">
            <el-radio v-model="form.bPortStatus" label="up" class="up">{{$t('开启')}}</el-radio>
            <el-radio v-model="form.bPortStatus" label="down" class="down">{{$t('关闭')}}</el-radio>
          </el-form-item>
          <el-form-item :label="$t('聚合ID')" :label-width="formLabelWidth" prop="BondId" v-if="[2].includes(form.enPortMode)">
            <el-select v-model="form.BondId" ref="bondId" :placeholder="$t('请选择')"><!--  :disabled='bondIdDisabled' -->
              <el-option v-for="item in BondIdList" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div v-if="form.enPortMode === 0">
          <el-form-item :label="$t('IPv4网关(策略路由使用)')" prop="cPortIpv4Gateway" :label-width="formLabelWidth" @input="updateView($event)">
            <el-input v-emoji v-model="form.cPortIpv4Gateway" ref="ipv4Gateway" style="width:275px;">
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('IPv6网关(策略路由使用)')" prop="cPortIpv6Gateway" :label-width="formLabelWidth" @input="updateView($event)">
            <el-input v-emoji v-model="form.cPortIpv6Gateway" ref="ipv6Gateway" style="width:275px;">
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('出方向带宽(策略路由使用)')" prop="iOutbandwidth" :label-width="formLabelWidth" @input="updateView($event)">
            <el-input v-emoji v-model="form.iOutbandwidth" ref="outBandwidth" style="width: 50%">
            </el-input>
            <span> - </span>
            <el-select v-model="form.OutbandwidthUnit" ref="outbandwidthUnit" :placeholder="$t('请选择')" style="width: 40%">
              <el-option :label="'Kbps'" :value="'Kbps'"></el-option>
              <el-option :label="'Mbps'" :value="'Mbps'"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div v-if="form.enPortMode === 1">
          <el-form-item :label="$t('链路类型')" :label-width="formLabelWidth">
            <el-radio v-model="form.PHYSICS_PORT_TYPE" :label="0" class="access">access</el-radio>
            <el-radio v-model="form.PHYSICS_PORT_TYPE" :label="1" class="trunk">trunk</el-radio>
            <el-radio v-model="form.PHYSICS_PORT_TYPE" :label="2" class="hybrid">hybrid</el-radio>
          </el-form-item>
        </div>
        <div v-if="form.enPortMode === 1 && form.PHYSICS_PORT_TYPE === 0">
          <el-form-item label='Access VLAN Id' prop="iVlanId" :label-width="formLabelWidth" @input="updateView($event)">
            <el-input v-emoji v-model="form.iVlanId" ref="viewVlanId" key="viewVlanId"></el-input>
          </el-form-item>
        </div>
        <div v-if="form.enPortMode === 1 && form.PHYSICS_PORT_TYPE === 1">
          <el-form-item label="Trunk VLAN Id" :label-width="formLabelWidth">
            <el-input v-emoji v-model="form.iAllowed" ref="trunkVlanId" :placeholder="$t('请输入(1-4094,例如：1,3,5-10)')" @input="updateView($event)" style="width:275px;"></el-input>
          </el-form-item>
          <el-form-item label="Default VLAN Id" prop="iVlanId" :label-width="formLabelWidth" @input="updateView($event)">
            <el-input v-emoji v-model="form.iVlanId" ref="defVlanId" key="defVlanId" style="width:275px;"></el-input>
            <!-- <p style="font-size:12px;color:red;">{{$t('请根据实际设置trunk区间，区间较大时耗时较长')}}</p> -->
          </el-form-item>
        </div>
        <div v-if="form.enPortMode === 1 && form.PHYSICS_PORT_TYPE === 2">
          <el-form-item :label="$t('Hybrid VLAN Id(带VLAN Tag)')" :label-width="formLabelWidth">
            <el-input v-emoji v-model="form.Tagged" id="physical-tagged" :placeholder="$t('请输入(1-4094,例如：1,3,5-10)')" @input="updateView($event)" style="width:275px;"></el-input>
          </el-form-item>
          <el-form-item :label="$t('Hybrid VLAN Id(不带VLAN Tag)')" :label-width="formLabelWidth">
            <el-input v-emoji v-model="form.Untagged" id="physical-untagged" ref="untagged" :placeholder="$t('请输入(1-4094,例如：1,3,5-10)')" @input="updateView($event)" style="width:275px;"></el-input>
          </el-form-item>
          <el-form-item label="Default VLAN Id" prop="iVlanId" :label-width="formLabelWidth" @input="updateView($event)">
            <el-input v-emoji v-model="form.iVlanId" ref="hyVlanId" key="hyVlanId" style="width:275px;"></el-input>
            <!-- <p style="font-size:12px;color:red;">{{$t('请根据实际设置hybrid区间，区间较大时耗时较长')}}</p> -->
          </el-form-item>
        </div>
      </el-col>
    </el-row>

    <div v-if="form.enPortMode === 0">
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="IPv4" name="ipv4">
          <!--    添加对象页面-->
          <div>
            <el-button type="success" :size="'small'" @click="add_addr4" class="ipv4Add">{{$t('添加')}}</el-button>
            <el-dialog :close-on-click-modal='false' v-drag :title="$t('添加')" :v-if="dialogAddr4FormVisible" :visible.sync="dialogAddr4FormVisible" width="400px" append-to-body>
              <el-form :model="add_ipv4_form" :rules="add_rules" :hide-required-asterisk="true" ref="add_ipv4_form" class="demo-ruleForm" :label-position="labelPosition" style="margin:0 20px;">
                <el-form-item :label="$t('IP地址')" :label-width="addWidth" :prop="'ipv4'">
                  <el-input v-emoji v-model="add_ipv4_form.ipv4" ref="ip4" style="width:217px;" size='small'></el-input>
                </el-form-item>
                <el-form-item :label="$t('子网掩码')" :label-width="addWidth" :prop="'mask'">
                  <el-input v-emoji v-model="add_ipv4_form.mask" ref="mask" style="width:217px;" size='small'></el-input>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm('add_ipv4_form')" class="innerAddSubmit1">{{$t('确 定')}}</el-button>
                <el-button @click="dialogAddr4FormVisible = false" class="innerAddClose1">{{$t('取 消')}}</el-button>
              </div>
            </el-dialog>

            <el-table size='mini' :data="form.ipv4" stripe border style="width: 100%;margin-top: 5px">
              <el-table-column prop='cPortIpv4' label="IPv4" align="center">
                <template slot-scope="scope">
                  <tooltip :html="scope.row.cPortIpv4" :content="scope.row.cPortIpv4" class="wid190" :refName="scope.row.cPortIpv4">
                  </tooltip>
                </template>
              </el-table-column>
              <el-table-column prop='cPortNetmask' :label="$t('子网掩码')" align="center">
                <template slot-scope="scope">
                  <tooltip :html="scope.row.cPortNetmask" :content="scope.row.cPortNetmask" class="wid190" :refName="scope.row.cPortNetmask">
                  </tooltip>
                </template>
              </el-table-column>
              <el-table-column fixed="right" :label="$t('操作')" width="100" align="center">
                <template slot-scope="scope">
                  <el-button @click.native.prevent="deleteRow(scope.$index, form.ipv4)" :class="'del' + scope.$index" type="danger" plain size="mini">
                    {{$t('删除')}}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="IPv6" name="ipv6">
          <!--    添加对象页面-->
          <div v-if="loading === 'ipv6'">
            <el-button type="success" size="small" @click="add_addr6" class="ipv6Add">{{$t('添加')}}</el-button>
            <el-dialog :close-on-click-modal='false' v-drag :title="$t('添加')" v-if="dialogAddr6FormVisible" :visible.sync="dialogAddr6FormVisible" width="400px" append-to-body>
              <el-form :model="add_ipv6_form" :rules="add_rules" :hide-required-asterisk="true" ref="add_ipv6_form" class="demo-ruleForm" :label-position="labelPosition" style="margin:0 20px;">
                <el-form-item :label="$t('IP地址')" :label-width="addWidth" :prop="'ipv6'">
                  <el-input v-emoji v-model="add_ipv6_form.ipv6" ref="ip6" style="width:217px;" size='small'></el-input>
                </el-form-item>
                <el-form-item :label="$t('前缀长度')" :label-width="addWidth" :prop="'ex_len'">
                  <el-input v-emoji v-model.number="add_ipv6_form.ex_len" ref="len" style="width:217px;" size='small'></el-input>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm_ipv6('add_ipv6_form')" class="innerAddSubmit2">{{$t('确 定')}}</el-button>
                <el-button @click="dialogAddr6FormVisible = false" class="innerAddClose2">{{$t('取 消')}}</el-button>
              </div>
            </el-dialog>

            <el-table size='mini' :data="form.ipv6" stripe border style="width: 100%;margin-top: 5px">
              <el-table-column prop='cPortIpv6' label="IPv6" align="center">
                <template slot-scope="scope">
                  <tooltip :html="scope.row.cPortIpv6" :content="scope.row.cPortIpv6" class="wid190" :refName="scope.row.cPortIpv6">
                  </tooltip>
                </template>
              </el-table-column>
              <el-table-column prop='cDevIpv6Prefix' :label="$t('前缀长度')" align="center">
                <template slot-scope="scope">
                  <tooltip :html="scope.row.cDevIpv6Prefix" :content="scope.row.cDevIpv6Prefix" class="wid190" :refName="scope.row.cDevIpv6Prefix">
                  </tooltip>
                </template>
              </el-table-column>
              <el-table-column fixed="right" :label="$t('操作')" width="100" align="center">
                <template slot-scope="scope">
                  <el-button @click.native.prevent="deleteRow(scope.$index, form.ipv6)" :class="'del' + scope.$index" type="danger" plain size="mini">
                    {{$t('删除')}}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

  </el-form>

</template>

<script>
import { getPhysicalApiInfo } from '@/api/network/api/physical'
import { inputClass, selectClass } from '@/utils/input-class.js'
export default {
  props: [
    'dialogFormVisible',
    'type_info',
    'edit_form',
    'addr_group_list'
  ],
  name: 'PhysicalEdit',
  data () {
    // var validateName = (rule, value, callback) => {
    //   if (!String(value).trim()) {
    //     callback(new Error(this.$t('请输入对象名称')))
    //   } else {
    //     callback()
    //   }
    // }
    var add_ipv4 = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('IP不能为空')))
      }
      if (!this.isValidIP(value)) {
        callback(new Error(this.$t('请输入正确的ip地址')))
      } else {
        callback()
      }
    }
    var mask = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('子网掩码不能为空')))
      }
      if (!this.isValidMask(value)) {
        callback(new Error(this.$t('请输入正确的子网掩码')))
      } else {
        callback()
      }
    }
    var add_ipv6 = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('IP不能为空')))
      }
      if (!this.isValidIPv6(value)) {
        callback(new Error(this.$t('请输入正确的ip地址')))
      } else {
        callback()
      }
    }
    var bond_id = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback()
      } else if (Number(value) > 15 || Number(value) < 0) {
        callback(new Error(this.$t('聚合ID的值为0-15')))
      } else {
        callback()
      }
    }
    var iVlan_id = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    var add_ex_len = (rule, value, callback) => {
      if (Number(value) < 1 || Number(value) > 128) {
        callback(new Error(this.$t('前缀长度的范围是1-128')))
      } else {
        callback()
      }
    }
    return {
      old_name: '',
      old_desc: '',
      old_form: {},
      old_iMtu: '',
      form: {
        strPhysicsName: '',
        strBridgeName: '',
        cDevOtherName: '',
        iMtu: '',
        bNegotiateFlag: 'on',
        bandwidth: null,
        bandwidthState: '状态未知！',
        bDuplexFlag: 'full',
        bDuplexFlagState: '状态未知！',
        enPortMode: 0,
        force_autoneg: false,
        bPortStatus: 'up',
        cPortIpv4Gateway: '',
        cPortIpv6Gateway: '',
        iOutbandwidth: '',
        OutbandwidthUnit: 'Kbps',
        PHYSICS_PORT_TYPE: 0,
        iAllowed: '',
        iVlanId: '',
        ipv4: [],
        ipv6: [],
        speed_list: [],
        iTransSelectedPort: '',
        iTransType: 1,
        iTransDirecType: 1,
        BondId: 0,
        Tagged:"",// hybrid vlan 带tag
        Untagged:"",// hybrid vlan 不带tag
      },
      formCopy: {
        strPhysicsName: '',
        strBridgeName: '',
        cDevOtherName: '',
        iMtu: '',
        bNegotiateFlag: 'on',
        bandwidth: null,
        bandwidthState: '状态未知！',
        bDuplexFlag: 'full',
        bDuplexFlagState: '状态未知！',
        enPortMode: 0,
        force_autoneg: false,
        bPortStatus: 'up',
        cPortIpv4Gateway: '',
        cPortIpv6Gateway: '',
        iOutbandwidth: '',
        OutbandwidthUnit: 'Kbps',
        PHYSICS_PORT_TYPE: 0,
        iAllowed: '',
        iVlanId: '',
        ipv4: [],
        ipv6: [],
        speed_list: [],
        iTransSelectedPort: '',
        iTransType: 1,
        iTransDirecType: 1,
        BondId: 0,
        Tagged:"",// hybrid vlan 带tag
        Untagged:"",// hybrid vlan 不带tag
      },
      rules: {
        // strPhysicsName: [{ required: false, validator: validateName, trigger: 'blur' }]
        // cDevOtherName: [{ required: false, validator: validateName, trigger: 'blur' }]
      },
      add_rules: {
        ipv4: [{ validator: add_ipv4, trigger: 'blur' }],
        mask: [{ validator: mask, trigger: 'blur' }],
        ipv6: [{ validator: add_ipv6, trigger: 'blur' }],
        BondId: [{ validator: bond_id, trigger: 'blur' }],
        iVlanId: [{ validator: iVlan_id, trigger: 'blur' }],
        iTransSelectedPort: [{ validator: iVlan_id, trigger: 'blur' }],
        ex_len: [
          { required: true, message: this.$t('前缀长度不能为空') },
          { type: 'number', message: this.$t('前缀长度必须为数字值') },
          { validator: add_ex_len, trigger: 'blur' }
        ]
      },
      // bondIdDisabled: false,
      physicsList: [],
      BondIdList: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
      add_ipv4_form: {},
      add_ipv6_form: {},
      lang: this.$i18n.locale,
      formLabelWidth: this.$i18n.locale === 'zh' ?'200px':'280px',
      formLabelWidthHalf:  this.$i18n.locale === 'zh' ?'100px':'200px',
      addWidth: '90px',
      dialogAddr4FormVisible: false,
      dialogAddr6FormVisible: false,
      labelPosition: 'left',
      activeName: 'ipv4',
      loading: ''
    }
  },
  mounted () {
    this.$nextTick(() => {
      const data = ['name']
      inputClass(this.$refs, data)
    })
  },
  computed: {
    change () {
      const { enPortMode, PHYSICS_PORT_TYPE, iTransType } = this.form
      return { enPortMode, PHYSICS_PORT_TYPE, iTransType }
    }
  },
  watch: {
    change: {
      handler (val) {
        if (val.enPortMode === 0) { // 路由模式
          this.$nextTick(() => {
            inputClass(this.$refs, ['ipv4Gateway', 'ipv6Gateway', 'outBandwidth'])
            inputClass(this.$refs, ['mtu'])
            selectClass(this.$refs, ['bandwidth', 'bDuplexFlag'])
            selectClass(this.$refs, ['outbandwidthUnit'])
          })
        } else if (val.enPortMode === 1) { // 透明模式
          this.$nextTick(() => {
            const inputData = ['mtu']
            inputClass(this.$refs, inputData)
            selectClass(this.$refs, ['bandwidth', 'bDuplexFlag'])
            if (val.PHYSICS_PORT_TYPE === 0) {
              const inputData0 = ['viewVlanId']
              inputClass(this.$refs, inputData0)
            } else if (val.PHYSICS_PORT_TYPE === 1) {
              const inputData1 = ['defVlanId', 'trunkVlanId']
              inputClass(this.$refs, inputData1)
            }
          })
        } else if (val.enPortMode === 2) { // 聚合模式
          this.$nextTick(() => {
            inputClass(this.$refs, ['mtu'])
            selectClass(this.$refs, ['bandwidth', 'bDuplexFlag', 'bondId'])
          })
        } else if (val.enPortMode === 3) { // 虚拟线模式
          this.$nextTick(() => {
            const selectData = ['port']
            selectClass(this.$refs, selectData)
            if (val.iTransType === 2) {
              const selectData2 = ['direcType']
              selectClass(this.$refs, selectData2)
            }
          })
        }
      }
    },
    edit_form: {
      handler (val) {
        if (this.type_info === '编辑') {
          this.form = Object.assign(this.form, val)
          // this.bondIdDisabled = !(val.BondId === '' || val.BondId === -1)
          this.form.BondId = (this.form.BondId === '' || this.form.BondId === -1) ? 0 : this.form.BondId
          if (!this.form.bandwidth && this.form.speed_list && this.form.speed_list.length > 0) {
            this.form.bandwidth = this.form.speed_list[this.form.speed_list.length - 1]
          }
          this.old_name = val.name
          this.old_desc = val.desc
          this.old_iMtu = val.iMtu
          this.old_form = JSON.parse(JSON.stringify(val))
          if (this.addr_group_list) {
            this.physicsList = []
            for (let index in this.addr_group_list) {
              if (this.addr_group_list[index].strPhysicsName !== this.form.strPhysicsName) {
                this.physicsList.push(this.addr_group_list[index])
              }
            }
          }
          if (this.form.enPortMode === 0) {
            this.$nextTick(() => {
              inputClass(this.$refs, ['ipv4Gateway', 'ipv6Gateway', 'outBandwidth', 'mtu'])
              selectClass(this.$refs, ['bandwidth', 'bDuplexFlag', 'outbandwidthUnit'])
            })
          }
        } else {
          this.form = Object.assign(this.form, val)
          if (!this.form.bandwidth && this.form.speed_list && this.form.speed_list.length > 0) {
            this.form.bandwidth = this.form.speed_list[this.form.speed_list.length - 1]
          }
        }
        if (this.form.enPortMode === 0) {
          if (this.form.ipv4.length > 0 && !this.form.ipv4[0].cPortIpv4) {
            this.form.ipv4.splice(0, 1)
          }
          if (this.form.ipv6.length > 0 && !this.form.ipv6[0].cDevIpv6Prefix) {
            this.form.ipv6.splice(0, 1)
          }
        }
      },
      immediate: true
    },
    'dialogAddr4FormVisible': {
      handler (val) {
        if (val === false) {
          this.add_ipv4_form = {}
          this.add_ipv6_form = {}
          if (this.$refs['add_ipv4_form'] !== undefined) {
            this.$refs['add_ipv4_form'].resetFields()
          }
          if (this.$refs['add_ipv6_form'] !== undefined) {
            this.$refs['add_ipv6_form'].resetFields()
          }
        }
      },
      immediate: true
    },
    'dialogAddr6FormVisible': {
      handler (val) {
        if (val === false) {
          this.add_ipv4_form = {}
          this.add_ipv6_form = {}
          if (this.$refs['add_ipv4_form'] !== undefined) {
            this.$refs['add_ipv4_form'].resetFields()
          }
          if (this.$refs['add_ipv6_form'] !== undefined) {
            this.$refs['add_ipv6_form'].resetFields()
          }
        }
      },
      immediate: true
    }
    // addr_group_list: {
    //   handler (val) {
    //     if (val) {
    //       this.physicsList = []
    //       for (let index in val) {
    //         if (val[index].strPhysicsName !== this.form.strPhysicsName) {
    //           this.physicsList.push(val[index])
    //         }
    //       }
    //     }
    //   },
    //   immediate: true
    // }
  },
  methods: {
    // 发送form表单数据到父组件
    send_form () {
      let childForm = {}
      if (this.form.enPortMode !== 3 && !this.form.iMtu) {
        this.$messages.error(this.$t('MTU不能为空'))
        return
      } else if (this.form.enPortMode !== 3 && (!this.isInteger(this.form.iMtu) || this.form.iMtu > 9216 || this.form.iMtu < 68)) {
        this.$messages.error(this.$t('MTU请输入68到9216之间的整数！'))
        return
      }
      if (this.form.enPortMode === 1 && this.form.PHYSICS_PORT_TYPE === 0) {
        if (!this.form.iVlanId) {
          this.$messages.error(this.$t('Access VLAN Id不能为空'))
          return
        } else if (!this.isInteger(this.form.iVlanId)) {
          this.$messages.error(this.$t('Access VLAN Id必须为整数数字'))
          return
        } else if (this.form.iVlanId > 4094 || this.form.iVlanId < 1) {
          this.$messages.error(this.$t('Access VLAN Id的范围为1到4094'))
          return
        }
      }
      if (this.form.enPortMode === 1 && this.form.PHYSICS_PORT_TYPE === 1) {
        if (!this.form.iVlanId) {
          this.$messages.error(this.$t('Default VLAN Id不能为空'))
          return
        } else if (!this.isInteger(this.form.iVlanId)) {
          this.$messages.error(this.$t('Default VLAN Id必须为整数数字'))
          return
        } else if (this.form.iVlanId > 4094 || this.form.iVlanId < 1) {
          this.$messages.error(this.$t('Default VLAN Id的范围为1到4094'))
          return
        }
        // const trunkStr = this.trunkCheck(this.form.iAllowed)
        // if (!this.form.iAllowed) {
        //   this.$messages.error(this.$t('Trunk VlanId不能为空'))
        //   return
        // } else if (trunkStr) {
        //   this.$messages.error(trunkStr)
        //   return
        // }
        if(this.form.iAllowed) {
           const trunkStr = this.trunkCheck(this.form.iAllowed,'Trunk VLAN Id')
          if (trunkStr) {
            this.$messages.error(trunkStr)
            return
          }
        }
      }
      if (this.form.enPortMode === 1 && this.form.PHYSICS_PORT_TYPE === 2) {
        if (!this.form.iVlanId) {
          this.$messages.error(this.$t('Default VLAN Id不能为空'))
          return
        } else if (!this.isInteger(this.form.iVlanId)) {
          this.$messages.error(this.$t('Default VLAN Id必须为整数数字'))
          return
        } else if (this.form.iVlanId > 4094 || this.form.iVlanId < 1) {
          this.$messages.error(this.$t('Default VLAN Id的范围为1到4094'))
          return
        }
        // const trunkStr = this.trunkCheck(this.form.iAllowed)
        // if (!this.form.iAllowed) {
        //   this.$messages.error(this.$t('Trunk VlanId不能为空'))
        //   return
        // } else if (trunkStr) {
        //   this.$messages.error(trunkStr)
        //   return
        // }
        if(this.form.Tagged) {
           const trunkStr = this.trunkCheck(this.form.Tagged,this.$t('Hybrid VLAN Id(带VLAN Tag)'))
          if (trunkStr) {
            this.$messages.error(trunkStr)
            return
          }
        }
         if(this.form.Untagged) {
           const trunkStr = this.trunkCheck(this.form.Untagged,this.$t('Hybrid VLAN Id(不带VLAN Tag)'))
          if (trunkStr) {
            this.$messages.error(trunkStr)
            return
          }
        }
      }
      if (this.form.enPortMode === 3 && !this.form.iTransSelectedPort) {
        this.$messages.error(this.$t('对端接口不能为空'))
        return
      }
      if (this.form.iOutbandwidth && this.form.enPortMode === 0 && this.form.OutbandwidthUnit === 'Mbps' && (this.form.iOutbandwidth > 1000 || this.form.iOutbandwidth < 1)) {
        this.$messages.error(this.$t('出方向带宽范围为 1-1000'))
        return
      }
      if (this.form.iOutbandwidth && this.form.enPortMode === 0 && this.form.OutbandwidthUnit === 'Kbps' && (this.form.iOutbandwidth > 1000000 || this.form.iOutbandwidth < 60)) {
        this.$messages.error(this.$t('出方向带宽范围为 60-1000000'))
        return
      }
      childForm.new_form = JSON.stringify(this.form)
      childForm.old_form = JSON.stringify(this.old_form)
      this.$emit('childForm', childForm)
    },
    updateView (e) {
      this.$forceUpdate()
    },
    add_addr4 () {
      this.dialogAddr4FormVisible = true
      this.$nextTick(() => {
        inputClass(this.$refs, ['ip4', 'mask'])
      })
    },
    add_addr6 () {
      this.dialogAddr6FormVisible = true
      this.$nextTick(() => {
        inputClass(this.$refs, ['ip6', 'len'])
      })
    },
    backParent () {
      this.$emit('quxiao', false)
    },
    deleteRow (index, rows) {
      rows.splice(index, 1)
    },
    handleClick (tab, event) {
      this.loading = tab.name
    },
    isValidIP (ip) {
      let reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
      return reg.test(ip)
    },
    isValidMask (mask) {
      let reg = /^(254|252|248|240|224|192|128|0)\.0\.0\.0|255\.(254|252|248|240|224|192|128|0)\.0\.0|255\.255\.(254|252|248|240|224|192|128|0)\.0|255\.255\.255\.(255|255|254|252|248|240|224|192|128|0)$/
      return reg.test(mask)
    },
    isValidIPv6 (ip) {
      // let reg = /^\s*((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}(:|((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})|(:[0-9A-Fa-f]{1,4})))|(([0-9A-Fa-f]{1,4}:){5}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){4}(:[0-9A-Fa-f]{1,4}){0,1}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4}){0,4}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))(%.+)?\s*$/
      let reg = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/
      return reg.test(ip)
    },
    trunkCheck (data,msg='') {
      let re = data
      let str = ''
      if (re.indexOf(',') > -1) {
        re = re.split(',')
        for (let item of re) {
          if (item.indexOf('-') > -1) {
            for (let bar of item.split('-')) {
              str = this.numCheck(bar,msg)
              if (str) return str
            }
          } else {
            str = this.numCheck(item,msg)
            if (str) return str
          }
        }
      } else if (re.indexOf('-') > -1) {
        for (let bar of re.split('-')) {
          str = this.numCheck(bar,msg)
          if (str) return str
        }
      } else {
        str = this.numCheck(re,msg)
        if (str) return str
      }
      return str
    },
    numCheck (value,msg) {
      if (!this.isInteger(value)) {
        return this.$t(`${msg}${this.$t('必须为整数数字')}`)
      } else if (Number(value) > 4094 || Number(value) < 1) {
        return this.$t(`${msg}${this.$t('的范围为1到4094')}`)
      }
      return ''
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let new_ipv4 = {}
          if (!this.form.ipv4) {
            this.form.ipv4 = []
          }
          new_ipv4.cPortIpv4 = this.add_ipv4_form.ipv4
          new_ipv4.cPortNetmask = this.add_ipv4_form.mask
          this.form.ipv4.push(new_ipv4)
          this.dialogAddr4FormVisible = false
        } else {
          return false
        }
      })
    },
    submitForm_ipv6 (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let new_ipv6 = {}
          if (!this.form.ipv6) {
            this.form.ipv6 = []
          }
          new_ipv6.cPortIpv6 = this.add_ipv6_form.ipv6
          new_ipv6.cDevIpv6Prefix = this.add_ipv6_form.ex_len
          this.form.ipv6.push(new_ipv6)
          this.dialogAddr6FormVisible = false
        } else {
          return false
        }
      })
    },
    close () {
      this.form = Object.assign({}, this.formCopy)
    },
    /**
     * [enPortModeChange 当模式切换为聚合模式时重置MTU的值]
     * @param  {[Number]}  data [模式]
     */
    enPortModeChange (data) {
      if (data === 2) {
        this.form.iMtu = this.old_iMtu
      }
    },
    isInteger (value) {
      return (!isNaN(value) && (parseInt(value).toString().length === String(Number(value)).length))
    },
    // 提交失败时刷新用
    newInfoChange () {
      getPhysicalApiInfo({ name: this.form.strPhysicsName }).then(res => {
        let val = res.info[0]
        // this.form = Object.assign(this.form, val)
        // this.form.BondId = (!this.form.BondId || this.form.BondId === -1) ? 0 : this.form.BondId
        this.old_name = val.name
        this.old_desc = val.desc
        this.old_iMtu = val.iMtu
        this.old_form = JSON.parse(JSON.stringify(val))
        // if (this.addr_group_list) {
        //   this.physicsList = []
        //   for (let index in this.addr_group_list) {
        //     if (this.addr_group_list[index].strPhysicsName !== this.form.strPhysicsName) {
        //       this.physicsList.push(this.addr_group_list[index])
        //     }
        //   }
        // }
        // if (this.form.enPortMode === 0) {
        //   if (this.form.ipv4.length > 0 && !this.form.ipv4[0].cPortIpv4) {
        //     this.form.ipv4.splice(0, 1)
        //   }
        //   if (this.form.ipv6.length > 0 && !this.form.ipv6[0].cDevIpv6Prefix) {
        //     this.form.ipv6.splice(0, 1)
        //   }
        // }
      })
    }
  }
}
</script>

<style scoped>
.warning_span {
  margin-left: 3%;
  color: red;
  font-size: 12px;
}
</style>
